package com.kefu.chat.service;

import java.util.List;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.kefu.chat.mapper.ChatRptDocHitMapper;
import com.kefu.robot.model.RobotDocType;
import com.kefu.robot.service.RobotDocTypeService;
import com.kefu.robot.vo.RobotDocTypeSearchVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.chat.vo.ChatRptDocHit;
import com.kefu.chat.vo.ChatRptDocHitSearchVo;
import com.kefu.common.service.AbstractKefuService;

import javax.annotation.Resource;

@Service
@Transactional
public class ChatRptDocHitService  extends AbstractKefuService<ChatRptDocHit>  {
	@Resource
    protected ChatRptDocHitMapper chatRptDocHitMapper;
	@Resource
	protected RobotDocTypeService robotDocTypeService;

	public Page<ChatRptDocHit> selectGroupByDate(ChatRptDocHitSearchVo vo) {
		Page<ChatRptDocHit> page = new Page<ChatRptDocHit>(vo.getPageNo(),vo.getPageSize(),true);
		page = chatRptDocHitMapper.staticsGroupByDate(page, vo);
		if(!page.getRecords().isEmpty()) {
			List<ChatRptDocHit> list = chatRptDocHitMapper.selectRobotInfo(page.getRecords().stream()
					.map(hit->hit.getDocId()).collect(Collectors.toList()));
			page.getRecords().forEach(hit->{
				list.stream().filter(robot->robot.getDocId().equals(hit.getDocId()))
				.findAny()
				.ifPresent(robot->{
					hit.setDocQuestion(robot.getDocQuestion());
					String docTypeId = robot.getDocTypeId();
					RobotDocType robotDocType = robotDocTypeService.findById(docTypeId);
					List<RobotDocType> robotDocTypeList = Lists.newArrayList();
					robotDocTypeService.getParent(robotDocType,robotDocTypeList);
					hit.setDocTypeName(robotDocTypeList.stream().map(RobotDocType::getName).collect(Collectors.joining("/")));
				});
			});
			List<ChatRptDocHit> collect = page.getRecords().stream().filter(hit -> hit.getDocQuestion() != null).collect(Collectors.toList());
			page.setRecords(collect);
			page.setTotal(collect.size());
		}
		return page;
	}


}
